package trans

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"mall/common/ctxdatax"
	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/backend/common/utils/pointy"
	userUtil "mall/service/forum/api/internal/logic/user/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/logic/util"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/user/rpc/userclient"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetTransactionListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetTransactionListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTransactionListLogic {
	return &GetTransactionListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetTransactionListLogic) GetTransactionList(req *types.TransactionListReq) (resp *types.TransactionListInfo, err error) {
	userId := ctxdatax.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	var preload string =
		"transaction:Id,AssetType,ChangeType,ChangeAmount,SourceType,SourceId,SourceDesc,CreatedAt"
	var eagerLoad string = "transaction:total"
	var filters []string
	filters = append(filters, "UserId,equalTo:" + strconv.FormatInt(int64(userId), 10))
	filters = append(filters, "Status,equalTo:" + strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	res, err := l.svcCtx.UserRpc.GetTransactionList(l.ctx, &userclient.BaseListReq{
		Offset:     uint32((page-1)*pageSize),
		Limit:      uint32(pageSize),
		Preload:    &preload,
		EagerLoad:  &eagerLoad,
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     req.Sorter,
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	logrus.Info(fmt.Sprintf("GetTransactionList: %+v", res))

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp = &types.TransactionListInfo{
		BaseListInfo: types.BaseListInfo{
			Current:         page,
			PageSize:        pageSize,
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	for _, v := range res.List {
		var assetTypeText string = userUtil.GetAssetTypeText(v.AssetType)
		income, _ := userUtil.GetChangeTypeText(v.ChangeType)
		var sourceTypeText string = userUtil.GetSourceTypeText(v.SourceType)

		resp.List = append(resp.List, &types.TransactionInfo{
			Id:             v.Id,
			AssetType:      v.AssetType,
			AssetTypeText:  assetTypeText,
			Income:         income,
			ChangeAmount:   v.ChangeAmount,
			SourceId:       v.SourceId,
			SourceType:     v.SourceType,
			SourceTypeText: sourceTypeText,
			SourceDesc:     v.SourceDesc,
			CreatedAt:      pointy.GetPointer(util.GetTimeFromNow(*v.CreatedAt)),
			UpdatedAt:      v.CreatedAt,
		})
	}

	return resp, nil
}
